import { Service } from 'egg';
import { Admin } from '../model/Admin';
import * as md5 from 'blueimp-md5';

export default class AdminService extends Service {
    /**
     * 处理后台登录事件
     * @param {string} admin_username
     * @param {string} admin_password
     * @returns {Promise<any>}
     */
    public async login(admin_username: string, admin_password: string) {
        admin_password = md5(admin_password + 'linglan');
        const admin = await this.ctx.model.Admin.findOne<Admin>({
            attributes: ['admin_id', 'admin_username', 'admin_password', 'admin_identity'],
            where: {
                admin_username,
                admin_password,
                admin_status: '1'
            },
        });
        if (!admin) {
            throw new Error(JSON.stringify({ code: '2', msg: '登录失败（用户名或密码错误）' }));
        }
        return admin;
    }

    /**
     * 更新token
     * @param {string} admin_username
     * @param {string} admin_token
     * @param {string} updated_time
     * @returns {Promise<any>}
     */
    public async updateToken(admin_id: string, admin_token: string) {
        const result = await this.ctx.model.Admin.update({ admin_token }, {
            where:
            {
                admin_id,
            },
        },
        );
        if (!result) {
            throw new Error(JSON.stringify({ code: '2', msg: '更新token失败' }));
        }
        return result;
    }

    /**
     *
     * @param token 根据token查找用户
     */
    public async searchAdminByToken(token: string) {
        const admin = await this.ctx.model.Admin.findOne<Admin>({
            attributes: ['admin_username', 'admin_password'],
            where: {
                admin_token: token,
            },
        });
        if (!admin) {
            throw new Error(JSON.stringify({ code: '-1', msg: '您还未登录，请登录' }));
        }
        return admin;
    }

    public async searchAdmin(username: string) {
        const admin = await this.ctx.model.Admin.findOne<Admin>({
            where: {
                admin_username: username,
            },
        });
        return admin;
    }

    /**
     * 新增管理员
     * @param param 
     */
    public async createAdmin(param: any) {
        const submitData: any = {};
        submitData.admin_id = this.ctx.helper.genUUID();
        submitData.admin_username = param.admin_username;
        submitData.admin_password = md5(param.admin_password + 'linglan');
        submitData.admin_token = '';
        submitData.admin_identity = param.admin_identity;
        submitData.admin_status = '1';
        submitData.is_delete = '1';
        const result = await this.ctx.model.Admin.create(submitData);
        if (!result) {
            throw new Error(JSON.stringify({ code: 2, msg: '新增失败' }));
        }
    }

    /**
     * 删除管理员
     * @param param 
     */
    public async deleteAdmin(param: any) {
        const result = await this.ctx.model.Admin.update({ is_delete: '2' }, { where: { admin_id: param.admin_id } });
        if (result[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '删除失败' }));
        }
    }

    /**
     * 查找管理员
     * @param param
     */
    public async searchAdminByParam(param: any) {
        const submitData: any = {};
        const Op = this.ctx.model.Op;
        if (!param.admin_username) {
            submitData.is_delete = '1';
        } else {
            submitData.is_delete = '1';
            submitData.admin_username = { [Op.like]: '%' + param.admin_username + '%' };
        }
        const admin: any = await this.ctx.model.Admin.findAll<Admin>({
            attributes: ['admin_id', 'admin_username', 'admin_identity', 'admin_status', 'created_at'],
            where: submitData,
        });
        if (admin.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        return admin;
    }

    /**
     * 修改管理员
     */
    public async udpateAdmin(param: any) {
        const submitData: any = {};
        if (param.admin_username) {
            submitData.admin_username = param.admin_username;
        }
        if (param.admin_password) {
            const admin_password = md5(param.admin_password + 'linglan');
            submitData.admin_password = admin_password;
        }
        if (param.admin_identity) {
            submitData.admin_identity = param.admin_identity;
        }
        const result = await this.ctx.model.Admin.update(submitData,
            {
                where: { admin_id: param.admin_id }
            });
        if (result[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
        }
    }

    /**
     * 启用，停用管理员
     */
    public async startAndStopAdmin(param: any) {
        const result = await this.ctx.model.Admin.update({ admin_status: param.type }, { where: { admin_id: param.admin_id } });
        if (result[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
        }
    }

}
